﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace katOS
{
    class SJF: AbstractQueue<Process>
    {
        public SJF(int id, string name, int quantum, bool preemptive, int queueOnEnd, int queueOnIOEnd)
        {
            this.id = id;
            this.name = name;
            this.quantum = quantum;
            this.preemptive = preemptive;
            this.queueOnQuantumEnd = queueOnEnd;
            this.queueOnIOEnd = queueOnIOEnd;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        public override Process getElement(int i)
        //public Process getElement(int i)
        {
            return this.list.ElementAt(i);
        }

        public override Process getLastProcess()
        //public Process getLastProcess()
        {
            return this.lastone_in;
        }

        public override void addProcess(Process new_process)
        {
            list.AddLast(new_process);
            lastone_in = new_process;
            Process temp = list.ElementAt(0);
            LinkedList<Process> temp_list = new LinkedList<Process>();
            SortedList<int, Process> sortedlist = new SortedList<int, Process>();

            this.lastone_in.setQuantumLeft(quantum);
            this.lastone_in.setState(2);
            this.lastone_in.io_wait = false;

            for (int i = 0; i < this.list.Count; i++)
            {
                sortedlist.Add(EcuationSJF(list.ElementAt(i)), list.ElementAt(i));
                Remove(list.ElementAt(i));
            }

            for (int i = 0; i < sortedlist.Count; i++)
            {
                list.AddLast(sortedlist.ElementAt(i).Value);
            }

            if (this.preemptive)
            {
                this.list.Remove(temp);
                this.list.AddFirst(temp);
            }
              
        }

        public override Process getFirst()
        {
            return this.list.ElementAt(0);
        }

        private int EcuationSJF(Process a_process)
        {
            Parser a_parser = new Parser();
            a_process.setInstructions(a_parser.getInstructionSet(a_process, a_process.getFileName()));
            int io_counter=0;
            for(int i=0; i<a_process.getInstructions().Count(); i++)
            {
                if(a_process.getInstructions().ElementAt(i).Equals("echo")||a_process.getInstructions().ElementAt(i).Equals("openfile")||a_process.getInstructions().ElementAt(i).Equals("readline")||a_process.getInstructions().ElementAt(i).Equals("closefile"))
                {
                    io_counter++;
                }
            }
            int total = (io_counter + a_process.getSymbolsTable().Length) / a_process.getInstructions().Count;    
            return total;
        }
    }
}
